﻿using System;
using RestSharp;
using Ayatta.Contract.Domain;
using Ayatta.Contract.Component;
using System.Collections.Specialized;

namespace Web.Base.OnlinePays
{
    internal abstract class OnlinePay : IOnlinePay
    {
        protected const int Timeout = 5000;
        protected readonly IRestClient Client;

        protected string BaseUrl { get; set; }
        protected string DefaultKey { get; set; }

        /// <summary>
        /// 接收到第三方平台通知并验证通过后触发
        /// </summary>
        public Func<Notification, bool> Notityed { get; set; }

        /// <summary>
        /// 第三方支付平台配置信息
        /// </summary>
        protected PaymentPlatform Platform { get; private set; }

        /// <summary>
        /// 在线支付
        /// </summary>
        /// <param name="platform">第三方支付平台配置信息</param>
        protected OnlinePay(PaymentPlatform platform)
        {
            Platform = platform;
            Client = new RestClient();
        }

        /// <summary>
        /// 接收到第三方平台通知并验证通过后触发
        /// </summary>
        /// <param name="e"></param>
        protected virtual bool OnNotityed(Notification e)
        {
            var handler = Notityed;
            return handler != null && handler(e);
        }

        /// <summary>
        /// 生成支付请求Url
        /// </summary>
        /// <returns></returns>
        public abstract string GetPayUrl(PayTrade trade);

        /// <summary>
        /// 处理支付平台通知
        /// </summary>
        /// <param name="nv">第三方支付平台通知参数</param>
        /// <returns></returns>
        public abstract SkResult<Notification> NotityHandler(NameValueCollection nv);

        ///// <summary>
        ///// 生成QueryString
        ///// </summary>
        ///// <param name="nvc"></param>
        ///// <returns></returns>
        //protected static string GetParamString(NameValueCollection nvc)
        //{
        //    var param = HttpUtility.ParseQueryString(string.Empty);
        //    foreach (var key in nvc.AllKeys)
        //    {
        //        param.Add(key, nvc[key]);
        //    }
        //    return param.ToString();
        //}
    }
}